package com.ccys.cms.controller.inventory;

import com.ccys.cms.service.inventory.PurchaseDetailLogService;
import com.ccys.cms.service.inventory.PurchaseOrderDetailService;
import com.ccys.cms.service.inventory.PurchaseOrderService;
import com.ccys.cms.service.productAndService.ProductService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.web.inventory.InventoryListDto;
import com.ccys.db.dto.web.inventory.ProductBatchDto;
import com.ccys.db.dto.web.inventory.UpdatePurchaseDetailStatusDto;
import com.ccys.db.entity.TblProduct;
import com.ccys.db.entity.TblPurchaseOrderDetail;
import com.ccys.db.entity.TblPurchaseOrderDetailLog;
import com.ccys.db.mapper.TblPurchaseOrderMapper;
import com.ccys.db.vo.web.inventory.InventoryListVo;
import com.ccys.db.vo.web.inventory.ProductBatchListVo;
import com.ccys.db.vo.web.inventory.ProductBatchVo;
import com.ccys.db.vo.web.inventory.ProductInfoVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/inventory")
@Api(tags = "库存产品")
public class InventoryListController {

    @Resource
    private PurchaseOrderService service;

    @Resource
    private PurchaseOrderDetailService detailService;

    @Resource
    private ProductService productService;

    @Resource
    private PurchaseDetailLogService logService;


    @Resource
    private TblPurchaseOrderMapper mapper;


    @ApiOperation(value = "查询分页",notes = "排序字段 t2.name / t2.group_name / t2.expiration_date / t2.quantity")
    @GetMapping("inventoryList")
    public ResponseResult<PageInfo<InventoryListVo>, Object> getPage(InventoryListDto dto) {
        return service.getInventoryPage(dto);
    }


    @ApiOperation("查询productInfo")
    @GetMapping("getProductInfo")
    public ResponseResult<ProductInfoVo,Object> getProductInfo(String productId){
        // TODO: 2023/12/19 0019 缺一个onhold字段 dosage form被排除了
        ProductInfoVo productInfo = productService.getProductInfo(productId);
        return ResponseResult.success(productInfo);
    }



    @ApiOperation(value = "查询productBatch分页",notes = "排序字段 t3.code(指的是purchaseNo) / t1.code(指的是batchNo) / t1.quantity(指的是totalQTY) /t2.qty_import_in_stock(指的是stock QTY)  / t1.amount (指的是totalcostprice) / t1.price_unit（指的是sellingprice）/t1.expiration_date/  t1.status / t1.created_on")
    @GetMapping("getProductBatchPage")
    public ResponseResult<PageInfo<ProductBatchVo>,Object> getProductBatchPage(ProductBatchDto dto){
        // TODO: 2023/12/19 0019 缺一个onhold字段
        return service.getProductBatch(dto);
    }


    @ApiOperation("查询productBatch集合")
    @GetMapping("getProductBatchList")
    public ResponseResult<List<ProductBatchListVo>,Object> getProductBatchList(){
        List<ProductBatchListVo> list = mapper.getProductBatchList();
        return ResponseResult.success(list);
    }


    @ApiOperation("修改某个批次的状态")
    @PutMapping("updateStatus")
    @Transactional
    public ResponseResult updateStatus(UpdatePurchaseDetailStatusDto dto) {
        String batchNo = dto.getBatchNo();
        Integer status = dto.getStatus();
        //1.修改批次状态
        TblPurchaseOrderDetail entityById = detailService.findOneByLimit(TblPurchaseOrderDetail.class,new ArrayList<String>(){{
            add("del_flag = 0");
            add("code = '"+batchNo+"'");
        }});

        if(Objects.nonNull(entityById)){
            entityById.setStatus(status);
            detailService.updateEntityById(entityById);
            //2.记录到detail_log(操作时实际库存，action)
            String productId = entityById.getProductId();
            TblProduct productEntity = productService.findEntityById(productId);
            Integer qtyRemainInStock = productEntity.getQtyRemainInStock();
            TblPurchaseOrderDetailLog logEntity = new TblPurchaseOrderDetailLog();
            logEntity.setOrderDetailId(entityById.getId());
            logEntity.setOrderDetailQuantityRemain(qtyRemainInStock);
            logEntity.setAction(status == 1 ? "active" : "inactive");
            int i = logService.insertOrUpdate(logEntity);
            // 修改库存总量
            if(status == 1){
                productService.increaseImportQuantity(entityById.getQuantity(),entityById.getProductId());
            }else{
                productService.decreaseImportQuantity(entityById.getQuantity(),entityById.getProductId());
            }
            return ResponseResult.update(i);
        }

        return ResponseResult.success();

    }


}
